package function;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import show.Main_show;
import util.JdbcUtil;

public class Message 
{
	private Connection conn = null;
	private ResultSet rs = null;
	private PreparedStatement ps = null;
	private String table = "message";
	private int id;
	private String n;
	private String txt;
	
	public Message(int id,String n,String txt)
	{
		this.id = id;
		this.n = n;
		this.txt = txt;
		
		conn = JdbcUtil.getConnection();		
		String sql = "insert into "+table+" values(?,?,?,now(),?,?)";
		try {
			ps = conn.prepareStatement(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	public void add() throws SQLException
	{
		Main_show m = new Main_show();
		int index = 0;
		rs = conn.createStatement().executeQuery("select * from message");
		while(rs.next())
		{
			try{
				index = rs.getInt(6)+1;
			}
			catch(Exception e)
			{
				index = 1;
			}
		}
		String name = (String) m.getNAME().get(m.getID().indexOf(id)); 
		try {
			ps.setString(1, name);
			ps.setString(2, n);
			ps.setString(3, txt);
			ps.setInt(4, id);
			ps.setInt(5, index);
			ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			JdbcUtil.release(conn, ps, rs);
		}
	}
//	public ResultSet getRs() {
//		if(conn!=null)
//			JdbcUtil.release(conn);
//		if(ps!=null)
//			JdbcUtil.release(ps);
//		if(rs!=null)
//			JdbcUtil.release(rs);
//		return rs;
//	}
	
//	public static void main(String[] args) 
//	{
//		Message m = new Message(20101913,"测试","hello world");
//		try {
//			m.add();
//		} catch (SQLException e) {
//			e.printStackTrace();
//		}
//	}	
}